package com.ihome.android.market2.frag;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ihome.android.EAFragment;
import com.ihome.android.academy.AlbumAppActivity;
import com.ihome.android.academy.CategoryAppActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetAlbumListTask;
import com.ihome.android.market2.info.TemplateContentInfo;
import com.ihome.android.market2.view.AlbumListItem;
import com.ihome.android.util.log.LogUtil;

public class AlbumListFragment extends EAFragment implements OnClickListener, OnKeyListener {
	private final String				TAG								= AlbumListFragment.class.getSimpleName();
	private View						fragview;

	private AlbumItemAdapter			mAdapter;
	private List<TemplateContentInfo>	mListAppPerPage					= new ArrayList<TemplateContentInfo>();
	private List<TemplateContentInfo>	mListAppTotal;

	@EAInjectView(id = R.id.gv_mgr_app)
	private GridView					mGridView;
	@EAInjectView(id = R.id.tv_page_pre)
	private TextView					tv_page_pre;
	@EAInjectView(id = R.id.tv_page_next)
	private TextView					tv_page_next;

	/** 该分类当前页数 */
	private int							mCurPage						= 1;
	/** 该分类APP总数 */
	private int							mAppNum							= 0;
	/** 每页展示的APP数量 */
	private final int					APPNUM_PER_PAGE					= 8;

	private final int					MSG_SPINEER_APP_LIST_REFRESH	= 3;
	private final int					MSG_SHOW_PREVIEW_PAGE			= 6;
	private final int					MSG_SHOW_NEXT_PAGE				= 8;

	private Handler						mHandler;

	private ImageLoader					imageLoader;
	private int							sectionId						= 0;

	public void setSectionId(int id){
		sectionId = id;
	}
	
	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SPINEER_APP_LIST_REFRESH:
					mCurPage = 1;
					getAlbumList();
					break;
				case MSG_SHOW_NEXT_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_NEXT_PAGE ------");
					if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
						mCurPage++;
						mAdapter.setCurPage(mCurPage);
						setPageLine();
					}
					break;
				case MSG_SHOW_PREVIEW_PAGE:
					LogUtil.v(TAG, " ------ MSG_SHOW_PREVIEW_PAGE ------");
					if (mCurPage > 1) {
						mCurPage--;
						mAdapter.setCurPage(mCurPage);
						setPageLine();
					}
					break;

				default:
					break;
				}
			}
		};
	}

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		LogUtil.i(TAG, "--> onAttach");

		imageLoader = ImageLoaderFactory.create(getActivity());
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.icon_default);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		procHandler();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, " -->  onCreateView()");
		fragview = (RelativeLayout) inflater.inflate(R.layout.frag_album_list, container, false);

		return fragview;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() ");
	}

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		LogUtil.i(TAG, " -->  setArguments()");
	}

	public void initData() {
		LogUtil.w(TAG, " -->  initData() ");
		if (mListAppTotal == null || mListAppTotal.size() == 0) {
			getAlbumList();
		}
		setPageLine();
	}

	public void focusGridView() {
		LogUtil.w(TAG, " -->  focusGridView() ");

		mAdapter.notifyDataSetChanged();
		mGridView.requestFocus();
	}

	private void init() {
		LogUtil.i(TAG, " -->  init()");

		mGridView.setFocusable(true);
		mGridView.setOnKeyListener(this);

		tv_page_pre.setOnClickListener(this);
		tv_page_next.setOnClickListener(this);

		initData();
	}

	/**
	 * 设置页数和APP总数
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void setPageLine() {
		mAppNum = mListAppTotal.size();

		if (mCurPage * APPNUM_PER_PAGE < mAppNum) {
			tv_page_next.setVisibility(View.VISIBLE);
		}

		if (mCurPage * APPNUM_PER_PAGE >= mAppNum) {
			tv_page_next.setVisibility(View.GONE);
			if (mAdapter != null)
				mAdapter.requestFocus();
		}

		if (mCurPage == 1) {
			tv_page_pre.setVisibility(View.GONE);
			if (mAdapter != null)
				mAdapter.requestFocus();
		}

		if (mCurPage > 1) {
			tv_page_pre.setVisibility(View.VISIBLE);
		}

	}

	private void getAlbumList() {
		LogUtil.i(TAG, " -->  getCategoryList()");

		int startIndex = (mCurPage - 1) * APPNUM_PER_PAGE;
		if (mListAppTotal == null)
			mListAppTotal = new ArrayList<TemplateContentInfo>();
		if (startIndex == 0)
			mListAppTotal.clear();

		Bundle b = new Bundle();
		b.putInt(HttpKeys.KEY_SECTIONID, sectionId);
		new GetAlbumListTask(getActivity(), this).execute(b);
	}

	public class AlbumItemAdapter extends BaseAdapter {
		private LayoutInflater	mInflater;
		private Context			context;

		private AlbumListItem	firstAppItem;
		private AlbumListItem	focusedAppItem;

		public AlbumItemAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
			setCurPage(1);
		}

		public void setCurPage(int mCurPage) {

			int total = mListAppTotal.size();
			int start = (mCurPage - 1) * APPNUM_PER_PAGE;
			int end = start + APPNUM_PER_PAGE;
			mListAppPerPage.clear();
			for (int i = start; i < total && i < end; i++) {
				mListAppPerPage.add(mListAppTotal.get(i));
			}

			notifyDataSetChanged();
		}

		@Override
		public int getCount() {

			return mListAppPerPage.size();
		}

		@Override
		public Object getItem(int position) {

			return mListAppPerPage.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		};

		public void requestFocus() {
			if (firstAppItem != null)
				firstAppItem.requestFocus();
		}

		public void setFocusedPosition(int position) {
			LogUtil.v(TAG, "setFocusedPosition() position = " + position);
			notifyDataSetChanged();

		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			AlbumListItem appItem;

			TemplateContentInfo appInfo = (TemplateContentInfo) getItem(position);

			if (null == convertView) {
				appItem = new AlbumListItem(context, imageLoader);
				convertView = appItem.getView();
				convertView.setTag(appItem);
			}
			else {
				appItem = (AlbumListItem) convertView.getTag();
			}

			appItem.initView(this, appInfo, position);

			if (position == 0) {
				firstAppItem = appItem;
			}

			appItem.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
						LogUtil.d(TAG, "album list item okey");
						
						TemplateContentInfo tmp = (TemplateContentInfo) getItem(position);
						Intent intent = new Intent(context, AlbumAppActivity.class);
						intent.putExtra(HttpKeys.KEY_SECTIONID, tmp.getContentId());
						intent.putExtra(AlbumAppActivity.APP_COLLECTION_NAME, tmp.getName());
						context.startActivity(intent);						
						
//						Intent intent = new Intent(context, AlbumAppActivity.class);
//						intent.putExtra(HttpKeys.KEY_SECTIONID, appInfo.getContentCode());
//						context.startActivity(intent);
						
					}
					return false;
				}
			});

			return convertView;
		}
	}

	/**
	 * 成功获取应用列表回调方法
	 * 
	 * @param mAppList
	 * @param appsNum
	 */
	public void getAppSuccess(List<TemplateContentInfo> mAppList, int appsNum) {
		LogUtil.d(TAG, "getAppSuccess > appsNum = " + appsNum);
		mAppNum = appsNum;
		mListAppTotal = mAppList;

		mAdapter = new AlbumItemAdapter(getActivity());
		mGridView.setAdapter(mAdapter);

		setPageLine();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_page_pre:
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			break;
		case R.id.tv_page_next:
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		LogUtil.v(TAG, " --> onKey() keyCode = " + keyCode);
		LogUtil.v(TAG, " --> onKey() mGridView.hasFocus() = " + mGridView.hasFocus());

		if (keyCode == KeyEvent.KEYCODE_PAGE_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_PREVIEW_PAGE);
			return true;
		}
		else if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
			mHandler.sendEmptyMessage(MSG_SHOW_NEXT_PAGE);
			return true;
		}

		if ((keyCode == KeyEvent.KEYCODE_PAGE_UP || keyCode == KeyEvent.KEYCODE_PAGE_DOWN) && event.getAction() == KeyEvent.ACTION_UP) {
			if (mGridView.hasFocus()) {
				mAdapter.requestFocus();
			}
		}

		return false;
	}
}
